﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;

namespace Warensoft.Unity.Communication.Client
{
    public static class CommonExtensions
    {
        public static void CopyTo(this Stream strmIn, Stream strmOut)
        {
            byte[] buffer = new byte[1024 * 4];
            int readLength= strmIn.Read(buffer, 0, buffer.Length);
            while (readLength !=0)
            {
                strmOut.Write(buffer ,0,readLength );
                readLength = strmIn.Read(buffer, 0, buffer.Length);
            }
        }
        /// <summary>
        /// 进行GZIP压缩
        /// </summary>
        /// <param name="buffer">压缩前的数据流</param>
        /// <returns>压缩后的数据流</returns>
        public static byte[] Zip(this byte[] buffer)
        {
            byte[] resultBuffer = null;
            using (MemoryStream msIn=new MemoryStream (buffer))
            {
                using (GZipStream zip=new GZipStream (msIn, CompressionMode.Compress ))
                {
                    using (MemoryStream msOut=new MemoryStream ())
                    {
                        zip.CopyTo(msOut);
                        resultBuffer = msOut.ToArray();
                    }
                }
            }
            return resultBuffer;
        }
        /// <summary>
        /// 进行GZIP解压缩
        /// </summary>
        /// <param name="buffer">解压缩前的数据流</param>
        /// <returns>解压缩后的数据流</returns>
        public static byte[] Unzip(this byte[] buffer)
        {
            byte[] resultBuffer = null;
            using (MemoryStream msIn = new MemoryStream(buffer))
            {
                using (GZipStream zip = new GZipStream(msIn, CompressionMode.Decompress))
                {
                    using (MemoryStream msOut = new MemoryStream())
                    {
                        zip.CopyTo(msOut);
                        resultBuffer = msOut.ToArray();
                    }
                }
            }
            return resultBuffer;
        }
    }
}
